package com.github.catvod.utils;

import com.github.catvod.net.OkHttp;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 图片验证码识别
 */
public class OCR {
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /**
     * 超级鹰识别打码
     * @return
     */
    private static String superEagleOCR(){
        return "";
    }

    /**
     * 获取百度识别验证token
     * @return
     */
    private static String get_token() throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token?client_id=wGyxP1ZKQ4oQv19B7snJVcZj&client_secret=kBNGVPKQlRsxcUot2R8qGxyWV9e2FGR5&grant_type=client_credentials")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject json = new JSONObject(response.body().string());
        return json.getString("access_token");
    }

    /**
     * 百度图片url验证码识别
     * @param img_url
     * @return
     */
    public static String OCR(String img_url) throws JSONException, IOException {
        String access_token = get_token();
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/numbers?access_token="+access_token;
        HashMap<String, String> params = new HashMap<>();
        params.put("url", img_url);
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        String body = OkHttp.post(url, params, headers).getBody();
        JSONObject json_body = new JSONObject(body);
        return json_body.getJSONArray("words_result").getJSONObject(0).getString("words");

    }
}
